<template>
	<view class="yz" :class="{'theme--Black':CurrentTheme.name==='DarkMode'}">
		
			<!-- 输入框 -->
			<div class="input-box">
				<text class="cuIcon-search"></text>
				<input class="input-inp" placeholder="搜索文件" />
			</div>
			<!-- 内容列表 -->
			<view class="list">
				<checkbox-group @change="checkboxChange">
					<!-- 文件夹 -->
					<view class="list-item" v-for="(i, j) in FolderList_C" :key="j" @click="onNextFolder(i.path)">
						<view style="display: flex; align-items: center;">
							<image class="list-item-img" src="../../../static/img/home/NewFolder.png"></image>
							<view class="list-item-txt">
								<text>{{ i.path | FolderPathFormat }}</text>
								<!-- <text class="item-txt-time">2020.07.16</text> -->
							</view>
						</view>
						<view @click.stop="onShow_DropDownPopup">
							<text v-if="!isShow_H5_Mask" class="cuIcon-round" style="font-size: 10rpx;"></text>
							<view v-else>
								<checkbox :class="i.checked ? 'checked' : ''" :checked="i.checked ? true : false" :value="i.path"></checkbox>
							</view>
						</view>
					</view>

					<!-- 文件 -->
					<view class="list-item" v-for="(i, j) in FileList_C" :key="FolderList_C.length + j">
						<view style="display: flex;">
							<load-img class="list-item-img" v-if="comIsImg('img', i.name)" mode="aspectFill" :src="i.url"></load-img>
							<image class="list-item-img" v-if="comIsImg('video', i.name)" src="../../../static/img/home/UploadVideo.png"></image>
							<image class="list-item-img" v-if="comIsImg('audio', i.name)" src="../../../static/img/home/UploadAudio.png"></image>
							<image class="list-item-img" v-if="comIsImg('doc', i.name)" src="../../../static/img/home/UploadDoc.png"></image>
							<image class="list-item-img" v-if="comIsImg('PPT', i.name)" src="../../../static/img/home/ppt.png"></image>
							<image class="list-item-img" v-if="comIsImg('HTML', i.name)" src="../../../static/img/home/HTML.png"></image>
							<image class="list-item-img" v-if="comIsImg('CSS', i.name)" src="../../../static/img/home/CSS.png"></image>
							<image class="list-item-img" v-if="comIsImg('JS', i.name)" src="../../../static/img/home/JS.png"></image>
							<image class="list-item-img" v-if="comIsImg('Vue', i.name)" src="../../../static/img/home/Vue.png"></image>
							<image class="list-item-img" v-if="comIsImg('JSON', i.name)" src="../../../static/img/home/JSON.png"></image>
							<image class="list-item-img" v-if="comIsImg('MD', i.name)" src="../../../static/img/home/MD.png"></image>
							<image class="list-item-img" v-if="comIsImg('PDF', i.name)" src="../../../static/img/home/pdf.png"></image>
							<image class="list-item-img" v-if="comIsImg('yasuo', i.name)" src="../../../static/img/home/yasuo.png"></image>
							<image class="list-item-img" v-if="$tool.getFileType(i.name) == 'adu'" src="../../../static/img/home/UploadDoc.png"></image>
							<view class="list-item-txt" @click="onItemDetail(i)">
								<text class="yy-txt-over1" style="width: 500rpx;">{{ i.name | FielPathFormat }}</text>
								<view class="flex align-center">
									<text class="item-txt-time">{{ $tool.formatDate(new Date(i.lastModified)) }}</text>
									<text class="item-txt-time ml20">{{ i.size | FileSizeFormat }}</text>
								</view>
							</view>
						</view>
						<view>
							<text @click.stop="onShow_DropDownPopup" v-if="!isShow_H5_Mask" class="cuIcon-round" style="font-size: 10rpx;"></text>
							<view v-else>
								<checkbox :class="i.checked ? 'checked' : ''" :checked="i.checked ? true : false" :value="i.name"></checkbox>
							</view>
						</view>
					</view>
				</checkbox-group>

				<!-- 无文件状态 -->
				<view class="norecord" v-if="FolderList_C.length == 0 && FileList_C.length == 0">
					<image src="../../../static/img/file/noFIle.png"></image>
					<text class="fo-gray fo-30 mt30">该文件夹下暂无文件</text>
				</view>
			</view><!-- #ifdef H5 -->
			<view style="width: 100%;height: 50px;"> </view>
			<!-- #endif -->
			<!-- #ifdef APP-PLUS -->
			<!-- 占位块 （用来点击文件操作栏添加个小块） -->
			<view v-if="isShow_H5_Mask" style="width: 100%;height: 50px;"> </view>
			<!-- #endif -->
			
		<!-- 上弹窗 -->
		<DropDown :isShow_H5_Mask.sync="isShow_H5_Mask" position="top" :isMask="false">
			<view slot="content" class="top-list">
				<text class="top-list-btn" @click="onDropDownCancel">取消</text>
				<text class="top-list-num">已选中{{ SeletedFileOrFolderCount }}个文件</text>
				<text class="top-list-btn" @click="onSelCheckALL">{{ SeletedFileOrFolderCount == 0 ? '全选' : '取消全选' }}</text>
			</view>
		</DropDown>
		
		<!-- 下弹窗 -->
		<DropDown :isShow_H5_Mask.sync="isShow_H5_Mask" position="bottom" :isMask="false">
			<view slot="content" class="bottom-list">
				<view class="bottom-list-item" @click="onDownload">
					<text class="cuIcon-down"></text>
					<text>下载</text>
				</view>
				<view class="bottom-list-item">
					<text class="cuIcon-share"></text>
					<text>分享</text>
				</view>
				<view class="bottom-list-item" @click="onDelte">
					<text class="cuIcon-delete"></text>
					<text>删除</text>
				</view>
				<view class="bottom-list-item">
					<text class="cuIcon-cuIcon"></text>
					<text>重命名</text>
				</view>
				<view class="bottom-list-item">
					<text class="cuIcon-more"></text>
					<text>更多</text>
				</view>
			</view>
		</DropDown>
	</view>
</template>

<script>
	import loadImg from '@/components/loadImg/index.vue';
	
	import {
		mapGetters
	} from 'vuex';
	import DropDown from '../../public/DropDownPopup.vue';
	import {
		API$DelFile
	} from '../../../common/API/file.js';
	export default {
		props: ['FolderList', 'FileList'],
		name: '',
		components: {
			DropDown,
			loadImg
		},
		data() {
			return {
				isShow_H5_Mask: false, // DropDownPopup是否显示(文件操作栏)
				FolderList_C: [],
				FileList_C: [],
				CheckList: [], // checkbox选中列表
				SeletedFileOrFolderCount: 0, //选中的文件/文件夹数目
				SeletedCurrentDownloadFile: [] // 选中当前要下载的文件

				
			};
		},
		watch: {
			FolderList() {
				this.FolderList_C = this.FolderList;
			},
			FileList() {
				this.FileList_C = this.FileList;
				this.ComputedFileOrFolderCount();
			},
			isShow_H5_Mask() {
				this.isShow_H5_Mask ? uni.hideTabBar({
					animation: true
				}) : uni.showTabBar({
					animation: true
				});
			}
		},
		computed: {
			// 计算是否是图片资源
			comIsImg() {
				return (type, str) => {
					if (type == 'img') {
						return this.$tool.ImgTypes(this.$tool.getFileType(str));
					} else if (type == 'video') {
						return this.$tool.ViodeoTypes(this.$tool.getFileType(str));
					} else if (type == 'doc') {
						return this.$tool.DocTypes(this.$tool.getFileType(str));
					} else if (type == 'audio') {
						return this.$tool.AudioTypes(this.$tool.getFileType(str));
					} else if (type == 'HTML') {
						return this.$tool.getFileType(str) == 'html';
					} else if (type == 'CSS') {
						return this.$tool.getFileType(str) == 'css';
					} else if (type == 'JS') {
						return this.$tool.getFileType(str) == 'js';
					} else if (type == 'Vue') {
						return this.$tool.getFileType(str) == 'vue';
					} else if (type == 'JSON') {
						return this.$tool.getFileType(str) == 'json';
					} else if (type == 'MD') {
						return this.$tool.getFileType(str) == 'md';
					} else if (type == 'PDF') {
						return this.$tool.getFileType(str) == 'pdf';
					} else if (type == 'PPT') {
						return this.$tool.PPTTypes(this.$tool.getFileType(str));
					} else if (type == 'yasuo') {
						return this.$tool.yasuoTypes(this.$tool.getFileType(str));
					}
				};
			},
			...mapGetters(['File_Get_OssClient'])
		},
		created() {
			console.log('页面created');
		},
		onShow() {
			console.log('页面显示');
		},
		mounted() {
			console.log('页面mounted');
		},
		methods: {
			// 显示工具操作栏
			onShow_DropDownPopup() {
				this.isShow_H5_Mask = true;
			},
			// 取消文件操作的弹窗
			onDropDownCancel() {
				this.isShow_H5_Mask = false;
				this.FolderList_C.forEach(i => {
					i.checked = false;
				});
				this.FileList_C.forEach(i => {
					i.checked = false;
				});
				this.ComputedFileOrFolderCount();
				this.ComputedSeletedCurrentDownloadFile();
			},
			// checkbox框改变触发
			checkboxChange(e) {
				let currList = e.detail.value;

				// 初始化false
				this.FolderList_C.forEach(i => {
					i.checked = false;
				});
				this.FileList_C.forEach(i => {
					i.checked = false;
				});

				// 遍历改变
				for (let i = 0, item;
					(item = currList[i]); i++) {
					for (let J = 0, Child;
						(Child = this.FolderList_C[J]); J++) {
						if (Child.path && Child.path == item) {
							Child['checked'] = !Child['checked'];
						}
					}
					for (let J = 0, Child;
						(Child = this.FileList_C[J]); J++) {
						if (Child.name && Child.name == item) {
							Child['checked'] = !Child['checked'];
						}
					}
				}
				this.ComputedFileOrFolderCount();
				this.ComputedSeletedCurrentDownloadFile();
			},
			// 计算选中的文件/文件夹数目
			ComputedFileOrFolderCount() {
				this.SeletedFileOrFolderCount = this.FolderList_C.filter(i => i.checked == true).length + this.FileList_C.filter(i =>
					i.checked == true).length;
			},
			// 计算 当前选中要下载的文件
			ComputedSeletedCurrentDownloadFile() {
				this.SeletedCurrentDownloadFile = [];
				this.FolderList_C.forEach(i => {
					if (i.checked == true) {
						this.SeletedCurrentDownloadFile.push(i);
					}
				});
				this.FileList_C.forEach(i => {
					if (i.checked == true) {
						this.SeletedCurrentDownloadFile.push(i);
					}
				});
			},
			// 全选按钮
			onSelCheckALL() {
				this.FolderList_C.forEach(i => {
					i.checked = this.SeletedFileOrFolderCount == 0 ? true : false;
				});
				this.FileList_C.forEach(i => {
					i.checked = this.SeletedFileOrFolderCount == 0 ? true : false;
				});
				this.ComputedFileOrFolderCount();
				this.ComputedSeletedCurrentDownloadFile();
			},
			// 点击文件进入详情
			onItemDetail(e) {
				console.log(e);
				if (this.$tool.ImgTypes(e.type)) {


					//  用于可以预览多张图片的数组参数
					let imgList = [],
						CurrentIndex = 0
					this.FileList_C.forEach((i, j) => {
						this.$tool.ImgTypes(i.type) ? imgList.push(i) : ""
						if (e.etag === i.etag) CurrentIndex = j
					})


					// 跳转图片显示页面
					this.$pub.naviTo(
						`/pages/other/ImgView/index?opt=${JSON.stringify(e)}&&imgList=${JSON.stringify(imgList)}&&CurrentIndex=${CurrentIndex}`
					);
					return;
				}
				if (this.$tool.ViodeoTypes(e.type)) {
					// 跳转视频显示页面
					this.$pub.naviTo(`/pages/other/VideoView/index?opt=${JSON.stringify(e)}`);
					return;
				}
			},
			// 文件夹联动
			onNextFolder(path) {
				// 文件操作栏显示状态下 不做联机操作
				if (this.isShow_H5_Mask) {
					return;
				}

				let pathList = path.split('/');
				let RealyPath = ''; // 处理后传给后端的路径
				for (let i in pathList) {
					if (!pathList[i] || i == 0) continue;
					RealyPath += pathList[i] + '/';
				}
				// 路径处理
				this.$emit('freshFolder', RealyPath);
			},
			/*************************************************************文件操作栏部分**************************************************************************/
			// 下载文件
			async onDownload() {
				// 校验选中列表是否包含文件夹
				let isSelFolder = false;
				for (let i = 0, item;
					(item = this.SeletedCurrentDownloadFile[i]); i++) {
					if (item.path && !item.name) {
						isSelFolder = true;
						break;
					}
				}
				if (isSelFolder) {
					return this.$pub.Toast('包含文件夹不可下载~')
				}

				let that = this;
				// 实例化 阿里oss对象
				this.$store.dispatch('Create_AliOssClient');

				let JsonPath = []; // 传给阿里云的访问路径
				for (let i = 0, item;
					(item = this.SeletedCurrentDownloadFile[i++]);) {
					item.name ? JsonPath.push(item.name) : '';
				} // 有过滤文件夹了
				console.log('传给阿里云的访问路径', JsonPath);
				let DownList = []; // 阿里云返回的临时下载地址
				for (let i = 0, item;
					(item = JsonPath[i]); i++) {
					let pathName = item.split('/')[item.split('/').length - 1]; //	asasfdas.video
					let FileName = pathName.slice(0, pathName.match(/[^\.]\w*$/).index - 1); //	asasfdas
					let FileType = this.$tool.getFileType(item); //	.video
					let filename = `${FileName}.${FileType}`; // filename为自定义下载后的文件名。
					let response = {
						'content-disposition': `attachment; filename=${encodeURIComponent(filename)}`
					};

					let pushIndex = this.SeletedCurrentDownloadFile.length - JsonPath.length;
					DownList.push({
						// fileObj:JSON.parse(JSON.stringify(this.SeletedCurrentDownloadFile[i+pushIndex])),
						fileName: filename,
						fileType: FileType,
						link: this.File_Get_OssClient.signatureUrl(item, {
							response
						})
					});
				}
				console.log('阿里云返回的临时下载地址', DownList);

				// #ifdef APP-PLUS
				// let TaskList = []
				for (let i = 0, item;
					(item = DownList[i]); i++) {
					let id = that.$tool.create_token();
					let objs = {
						// fileObj:item.fileObj,
						fileName: item.fileName,
						// fileSize: res.tempFiles[i].size,
						fileType: item.fileType,
						completeTime: null, // 下载完成时间

						progressTime: null, // 节流计时
						LastSecondSize: 0, // 上一秒已下载的量
						timer: null, // 轮询定时器（定时同步接口）
						Speed: 0, // 下载速度(字节为单位)
						progress: {
							totalSize: 0,
							curSize: 0,
							percent: 0 // 百分比
						},
						id,
						Task: plus.downloader.createDownload(item.link, {
							filename: '_downloads/yang/'
						}, function(download, status) {
							if (status == 200) {
								that.$pub.Toast('文件下载成功:' + download.filename + '~');

								let currentFilePath = plus.io.convertAbsoluteFileSystem(download.filename); // 取当前文件的绝对路径
								// let currentFilePath = plus.io.convertLocalFileSystemURL(download.filename); // 将本地URL路径转换成平台绝对路径

								// 将本地文件保存到相册 （只保存视频和图片） // TODO 后面写个缓存管理清空内部数据缓存
								if (that.$tool.ImgTypes(that.$tool.getFileType(download.filename))) {
									// console.log(currentFilePath);
									uni.saveImageToPhotosAlbum({
										filePath: currentFilePath,
										success: function() {
											that.$pub.Toast('图片已保存到相册');
											console.log('图片已保存到相册');
										},
										fail(e) {
											console.log('图片保存失败', e);
										}
									});
								} else if (that.$tool.ViodeoTypes(that.$tool.getFileType(download.filename))) {
									uni.saveVideoToPhotosAlbum({
										filePath: currentFilePath,
										success: function() {
											that.$pub.Toast('视频已保存到相册');
											console.log('视频已保存到相册');
										},
										fail(e) {
											console.log('视频保存失败', e);
										}
									});
								}

								that.$store.commit('ADD_CompleteDownloadTask_id', id);
								that.$store.commit('DEL_DownloadTask', id);
							} else {
								that.$pub.Toast('文件下载失败~');
							}
						})
					};
					console.log(objs);
					that.$store.commit('ADD_DownloadTask', objs);

					objs.Task.start();
					objs.Task.addEventListener('statechanged', function(task, status) {
						switch (task.state) {
							case 1: // 开始
								console.log('开始');
								break;
							case 2: // 已连接到服务器
								console.log('连接到服务器');
								break;
							case 3:
								let progress = parseInt((task.downloadedSize / task.totalSize) * 100);

								// 节流操作
								if (objs.progressTime) return
								objs.progressTime = setTimeout(() => {
									// console.log('下载进度：',progress)
									objs.progress.totalSize = that.$tool.comFileSize(task.totalSize);
									objs.progress.percent = progress;
									objs.Speed = task.downloadedSize - objs.LastSecondSize;
									objs.progress.curSize = that.$tool.comFileSize(task.downloadedSize);

									objs.LastSecondSize = task.downloadedSize // 便于计算速度
									clearTimeout(objs.progressTime)
									objs.progressTime = null
								}, 500)
								break;
							case 4:
								console.log('完成');
								objs.completeTime = that.$tool.create_time(new Date(), 'YYYYMMMDDHHMMSS');
								break;
						}
					});
				}

				this.onDropDownCancel();
				this.$nextTick(function() {
					setTimeout(() => {
						uni.$emit('changeSwitchBar', {
							TarBar: 1
						});
					}, 100);
					that.$pub.naviTo('/pages/public/TransferPopup/TransferManager'); // 跳转页面
					// that.$pub.naviTo('/pages/public/TransferPopup/index');
				});
				// #endif

				// #ifdef H5
				/***---web端执行--------A标签方法-***/
				// for (let i = 0, item; (item = DownList[i]); i++) {
				// 	let ele_a = document.createElement('a');
				// 	ele_a.href = item.link;
				// 	ele_a.download = '点击下载';
				// 	ele_a.click();
				// 	ele_a.remove();
				// }
				/***---web端执行--------ifrime方法-***/
				for (let i = 0, item;
					(item = DownList[i]); i++) {
					var ifr = document.createElement('iframe');
					ifr.style.display = 'none';
					ifr.src = item.link;
					document.body.appendChild(ifr);
					setTimeout(function() {
						ifr.remove();
						console.log(444);
					}, 1000);
				}
				this.onDropDownCancel();
				// #endif
			},
			// 删除文件
			async onDelte() {
				let dir = null;
				if (this.SeletedCurrentDownloadFile.length == 1) {
					dir = this.SeletedCurrentDownloadFile[0].name || this.SeletedCurrentDownloadFile[0].path;
				} else {
					dir = [];
					this.SeletedCurrentDownloadFile.forEach(async i => {
						dir.push(i.name || i.path);
					});
				}
				// console.log(dir)   //  15892023484/for循环.png
				let res = await API$DelFile({
					dir
				});
				if (res.code == 200) {
					this.$emit('freshFolder');
					setTimeout(() => {
						this.$pub.Toast('删除成功~');
					}, 1000);
				} else {
					this.$pub.Toast('请联系内部管理员~');
				}
				this.onDropDownCancel();
			}
		}
	};
</script>

<style lang="less" scoped='scoped'>
	page {
		background-color: #fff;
	}

	.yz {
		margin-top: 20rpx;
	}

	.input-box {
		padding: 12rpx 10px;
		width: 90%;
		margin: 0 auto;
		height: 30px;
		border-radius: 50px;
		display: flex;
		align-items: center;
		background-color: #f5f5f5;

		.input-inp {
			border: none;
			background-color: inherit;
			margin-left: 4px;
			font-size: 14px;
		}
	}

	// 内容列表
	.list {
		display: flex;
		flex-direction: column;

		.list-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx 40rpx;
			box-shadow: 0px 1px 0px #eaeaea;

			.list-item-img {
				height: 60rpx;
				width: 60rpx;
				margin-right: 30rpx;
			}

			.list-item-txt {
				display: flex;
				flex-direction: column;

				.item-txt-time {
					margin-top: 10rpx;
					color: gray;
					font-size: 20rpx;
				}
			}
		}
	}

	// 没有文件记录
	.norecord {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: absolute;
		left: 50%;
		top: 56%;
		transform: translate3d(-50%, -50%, 0);
		width: 100%;

		image {
			height: 160rpx;
			width: 160rpx;
		}
	}

	// 上弹窗
	.top-list {
		background-color: #fff;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 20rpx;

		.top-list-btn {
			color: #03a9f4;
		}

		.top-list-num {
			color: #000;
			font-size: 40rpx;
		}
	}

	// 下弹窗列
	.bottom-list {
		display: flex;
		background-color: #03a9f4;
		box-sizing: border-box;
		height: 110rpx;

		.bottom-list-item {
			flex: 1;
			padding: 20rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			color: #fff;

			text[class^='cuIcon-'] {
				font-size: 40rpx;
				color: #fff;
			}
		}
	}

	uni-checkbox .uni-checkbox-input {
		border: solid 1px gray !important;
	}



	// 图片懒加载类名穿透  .img 是内部类名
	/deep/ .img {
		height: 60rpx;
		width: 60rpx;
		border-radius: 10rpx;

		/deep/ image {
			border-radius: 10rpx;
			overflow: hidden;
		}
	}
</style>
